﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model;
using Model.Request;
using MongoDB.Driver;
using Model.Response;

namespace Services.Question
{
    public class QuestionServices
    {
        protected static MongoDbServices MongoDb = new MongoDbServices();

        /// <summary>
        /// 设置问卷方法
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static SetQuestionResponse SetQuestion( string data)
        {
            SetQuestionRequest request;
            try
            {
                request = JsonHelper.Deserialize<SetQuestionRequest>(data);
            }
            catch (Exception)
            {
                return new SetQuestionResponse() { ResponsesCode = (int)ResponseCode.ErrorFormal, ErrorMsg = "错误的请求格式" };
            }
            if (string.IsNullOrEmpty(request.QuestionPaperInfo.Serid))
            {
                //如果套餐流水号为空则生成一个  规则 TW+当前时间+三位随机数
                var ran = new Random(unchecked((int)DateTime.Now.Ticks));
                request.QuestionPaperInfo.Serid = string.Format("WJ{0}{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), ran.Next(100, 999));
            }
            request.QuestionPaperInfo.AddTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //if (Convert.ToDateTime(request.QuestionPaperInfo.AddTime) < Convert.ToDateTime("2001-01-01"))
            //{
            //    //如果是第一次新增则处理下新增 时间
            //    request.QuestionPaperInfo.AddTime = DateTime.Now.ToString(CultureInfo.InvariantCulture);
            //}

            var questionfilter = Builders<QustionPaper>.Filter.Eq("Serid", request.QuestionPaperInfo.Serid);
            var questionSetting = MongoDb.SimpleQueryMongoDb("QustionPaper", questionfilter).Result; //根据问卷套餐ID查一遍问卷套餐库 
            if (questionSetting != null)
            {
                //如果有数据则更新
                request.QuestionPaperInfo._id = questionSetting._id;
                var result = MongoDb.ReplaceMongoDb(request.QuestionPaperInfo, "QustionPaper", questionfilter).Result;
                return result.ModifiedCount > 0
                    ? new SetQuestionResponse() { ResponsesCode = (int)ResponseCode.Success, ErrorMsg = "更新成功" }
                    : new SetQuestionResponse() { ResponsesCode = (int)ResponseCode.DbError, ErrorMsg = "更新失败" };
            }

            MongoDb.InsertMongoDb(request.QuestionPaperInfo, "QustionPaper");
            return new SetQuestionResponse() {ResponsesCode = (int) ResponseCode.Success, ErrorMsg = "插入成功"};
        }

        /// <summary>
        /// 获取问卷套餐信息
        /// </summary>
        /// <param name="requestJson"></param>
        /// <returns></returns>
        public static GetAnswerRecordsResponse GetQuestionPaperInfo(string serid)
        {
            //GetAnswerRecordsRequest request;
            //try
            //{
            //    request = JsonHelper.Deserialize<GetAnswerRecordsRequest>(requestJson);
            //}
            //catch (Exception)
            //{
            //    return new GetAnswerRecordsResponse() {ResponsesCode = (int) ResponseCode.ErrorFormal, ErrorMsg = "错误的请求格式"};
            //}
            //if (request == null)
            //{
            //    return new GetAnswerRecordsResponse() {ResponsesCode = (int) ResponseCode.EmptyRequest, ErrorMsg = "错误的请求格式"};
            //}
            ////if (request.Key != SetQuestionKey)
            ////{
            ////    return new GetQuestionSettingInfoResponse() { IsSucess = false, ErrorMsg = "签名认证失败" };
            ////}

            //if (string.IsNullOrEmpty(request.SerId))
            //{
            //    return new GetAnswerRecordsResponse() {ResponsesCode = (int) ResponseCode.EmptyRequest, ErrorMsg = "问卷ID不能为空"};

            //}
            //if (string.IsNullOrEmpty(request.Ip))
            //{
            //    return new GetAnswerRecordsResponse() {ResponsesCode = (int) ResponseCode.EmptyRequest, ErrorMsg = "Ip不能为空"};

            //}

            var recordsResponse = new GetAnswerRecordsResponse();
            var filter = Builders<AnswerRecords>.Filter.Eq("PaperSerid", serid);
                         //& Builders<AnswerRecords>.Filter.Eq("Ip", request.Ip);
            var answerRecords = MongoDb.SimpleQueryMongoDb("AnswerRecordsInfo", filter).Result; //先去查一遍 答题库 
            if (answerRecords != null)
            {
                //有数据
                recordsResponse.IsAlreadyAnswer = true;
                recordsResponse.ResponsesCode = (int)(ResponseCode.Success);
                recordsResponse.AnswerRecords = answerRecords;
                return recordsResponse;
            }
            //没有数据（第一次答题）查一遍问卷套餐库
            var questionfilter = Builders<QustionPaper>.Filter.Eq("Serid", serid);
            var qustionPaper = MongoDb.SimpleQueryMongoDb("QustionPaper", questionfilter).Result; //查一遍问卷套餐库 

            if (qustionPaper == null)
            {
                return new GetAnswerRecordsResponse() { ResponsesCode = (int)ResponseCode.NoPaper, ErrorMsg = "未配置题库信息" };
            }
            //有数据
            var answerRe = new AnswerRecords
            {
                //Ip = request.Ip,
                PaperSerid = qustionPaper.Serid,
                AnswersTime = "2000-1-1",
            };

            var aquestList = qustionPaper.Question.Select(quest => new AnswerQuestion
            {
                QuestId = quest.Id,
                QuestType = quest.QType,
                OptionList = quest.OptionList,
                QuestTitle = quest.Title,
                Answer = null
            }).ToList();

            answerRe.AnswerQuestion = aquestList;

            recordsResponse = new GetAnswerRecordsResponse
            {
                IsAlreadyAnswer = false,
                ResponsesCode = (int)ResponseCode.Success,
                AnswerRecords = answerRe
            };
            return recordsResponse;
            //没有数据 返回错误
        }

        /// <summary>
        /// 保存答案信息
        /// </summary>
        /// <param name="requestJson"></param>
        /// <returns></returns>
        public static SaveAnswerRecodsResponse SaveAnswerRecords(string requestJson )
        {
            SaveAnswerRecodsRequset request;
            try
            {
                request = JsonHelper.Deserialize<SaveAnswerRecodsRequset>(requestJson);
            }
            catch (Exception ex)
            {
                return new SaveAnswerRecodsResponse() { ResponsesCode = (int)ResponseCode.ErrorFormal, ErrorMsg = "错误的请求格式" };
            }

            var answerRecordsRequest = request.AnswerRecords;
            if (answerRecordsRequest == null)
            {
                return new SaveAnswerRecodsResponse() { ResponsesCode = (int)ResponseCode.ErrorFormal, ErrorMsg = "错误的请求格式" };
            }
            answerRecordsRequest.AnswersTime = DateTime.Now.ToString();

            //获取题目为必答题但是答案为空的数据
            //var answerMsg = request.AnswerRecords.AnswerQuestion
            //    .Where(item => item.Question != null && item.Question.IsRequired && item.Answer == null)
            //    .Aggregate(string.Empty, (current, item) => current + (item.Question.OrderNum + ","));
            //if (!string.IsNullOrEmpty(answerMsg))
            //{
            //    return new AnswerTheQuestionResponse() { ResponsesCode = (int)ResponseCode.NotComplete, ErrorMsg = "第" + answerMsg + "题为必答题，请填写后再提交" };
            //}

            var filter = Builders<AnswerRecords>.Filter.Eq("PaperSerid", answerRecordsRequest.PaperSerid)
                         & Builders<AnswerRecords>.Filter.Eq("Ip", answerRecordsRequest.Ip);
            var answerRecords = MongoDb.SimpleQueryMongoDb("AnswerRecords", filter).Result; //先去查一遍 答题库 
            if (answerRecords != null)
            {
                //有数据则返回错误
                //request.AnswerRecords._id = answerRecords._id;
                //var result = MongoDb.ReplaceMongoDb(request.AnswerRecords, "AnswerRecordsInfo", filter).Result;
                //isSucess = result.ModifiedCount > 0;
                return new SaveAnswerRecodsResponse() { ResponsesCode = (int)ResponseCode.AlreadyExists, ErrorMsg = "已提交不能重复提交" };
            }

            MongoDb.InsertMongoDb(request.AnswerRecords, "AnswerRecordsInfo");
            //isSucess = true;
            // if (!isSucess) return new AnswerTheQuestionResponse() { ResponsesCode = (int)ResponseCode.DbError , ErrorMsg = "答题失败"};
            //答题成功回写预订信息
            return new SaveAnswerRecodsResponse() { ResponsesCode = (int)ResponseCode.Success, ErrorMsg = "答题成功" };

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userId"></param>
        public static List<QustionPaper>  GetPageList(int userId)
        {
            var filter = Builders<List<QustionPaper>>.Filter.Eq("AddNameId", userId);
            var qustionPapers = MongoDb.SimpleQueryMongoDb("QustionPaper", filter).Result; 
            if (qustionPapers != null)
            {
                return qustionPapers;
            }
            return new List<QustionPaper>();
        }
    }
}
